package com.rupertjones.globalcron.domain;

import org.hibernate.Criteria;
import org.springframework.stereotype.Repository;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static org.hibernate.criterion.Restrictions.eq;

/**
 * <p>&copy Rupert Jones 2011</p>
 *
 * @author rup
 */
@Repository
public class UserDAO extends AbstractHibernateDAO<User> {
    public UserDAO() {
        super(User.class);
    }

    public User login(String username, String password) {
        String hash = hash(password);
        Criteria criteria = getCriteria().add(eq("username", username)).add(eq("password", hash));
        return (User) criteria.uniqueResult();
    }

    public String hash(String value) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return "";
        }
        md.update(value.getBytes());
        byte[] byteData = md.digest();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

    public User findByUsername(String username) {
        Criteria criteria = getCriteria().add(eq("username", username));
        return (User) criteria.uniqueResult();
    }
}
